import { Component, OnInit, ElementRef, Input, OnChanges, SimpleChanges, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-dialog',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit, OnChanges, OnDestroy {

  imageUri: string;
  @Input() isVisible: boolean;
  @Input() container: any;
  private divElement: HTMLDivElement;
  constructor(private el: ElementRef) { }

  ngOnInit() {
    if (typeof(this.container) === 'string') {
      this.container = document.getElementById(this.container);
    } else if (typeof(this.container) === 'undefined' || !(<any>this.container instanceof (HTMLElement))) {
      this.container = document.body;
    }
    this.container = this.container || document.body;
    const containerElement = document.createElement('div');
    containerElement.tabIndex = -1;
    containerElement.setAttribute('style', 'position:absolute; left:0px; top:0px; width:100%; height:100%;');
    this.divElement = containerElement;
    this.divElement.appendChild(this.el.nativeElement);
    (<HTMLElement>this.container).appendChild(this.divElement);
    this.changeVisibleState();
    console.log(this.container);
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.isVisible) {
      this.changeVisibleState();
    }
  }
  ngOnDestroy() {
    if (this.divElement) {
      (<HTMLElement>this.container).removeChild(this.divElement);
    }
  }
  changeVisibleState() {
    if (this.divElement) {
      this.divElement.style.display = this.isVisible ? 'block' : 'none';
    }
  }
}
